
module Piston
  module Project
    class ProjectViewModel
      include Piston::ViewModelBase
      include System::Collections::ObjectModel

      declare_event :PropertyChanged
      
      attr_reader :name
      attr_accessor :root

      attr_reader :OpenProjectItem
      
      def initialize(name = nil)
        @name = name
        @title = name

        root_item = ProjectItem.new()
        root_item.name = "<<Project>>"

        @root = Collection[ProjectItem].new()
        @root.add root_item

        @OpenProjectItem = Piston::Project::OpenProjectItem.new(self)
      end

      def file_drop(files)
        root_item = ProjectItem.new()
        root_item.name = "<<Project>>"
        
        files.each do |file|
          if (File.file?(file))
            item = ProjectItem()
            item.file = file
            item.name = File.basename(file)
            root_item.children.add(item)
          else
            append_children(root_item, file)
          end
        end
        
        @root = Collection[ProjectItem].new()
        @root.add root_item
                
        RaisePropertyChanged("root")
      end

      def append_children(cur_item, directory)
        new_item = ProjectItem.new
        new_item.file = directory
        new_item.name = File.basename(directory)

        cur_item.children.add(new_item)

        files = Dir["#{directory}/*"]
        files.each do |file|
          if (File.file?(file))
            child = ProjectItem.new
            child.file = file
            child.name = File.basename(file)
            new_item.children.add(child)
          else
            append_children(new_item, file)
          end
        end
      end

      def perform_search
        matches = find_matches("hellle", @root)
        return if matches.empty?
        cur_item = matches[0]
        cur_item.is_selected = true
      end

      def find_matches(search_text, project_item)
        matches = []
        matches << project_item if project_item.contains_text?(search_text)
        project_item.children.each do |child|
          matches += find_matches(search_text, child)
        end
        return matches
      end
    end
  end
end